package com.hontech.bread.store

import androidx.core.database.sqlite.transaction
import com.hontech.bread.R
import com.hontech.bread.utils.runCPU
import com.hontech.bread.utils.stringById

class Config(val key: Int, val msg: String) {

    companion object {


        const val CREATE_SQL = "CREATE TABLE IF NOT EXISTS tb_config (" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "key INTEGER NOT NULL, " +
                "msg TEXT NOT NULL, " +
                "UNIQUE(key)" +
                ")"

        suspend fun save(key: Int, msg: String) = runCPU {
            Store.db.transaction {
                val cursor = rawQuery(
                    "SELECT key FROM tb_config WHERE key = ?",
                    arrayOf(key.toString())
                )
                val ret = cursor.use {
                    cursor.moveToNext()
                }
                if (ret) {
                    execSQL("UPDATE tb_config SET msg = ? WHERE key = ?", arrayOf(msg, key))
                } else {
                    execSQL("INSERT INTO tb_config (key, msg) VALUES (?, ?)", arrayOf(key, msg))
                }
            }
        }

        suspend fun get(key: Int): String = runCPU {

            val cursor = Store.db.rawQuery(
                "SELECT msg FROM tb_config WHERE key = ?",
                arrayOf(key.toString())
            )
            cursor.use {
                if (!cursor.moveToNext()) {
                    throw IllegalStateException(
                        "${stringById(R.string.t1733460848_283)} $key ${
                            stringById(
                                R.string.t1733460848_284
                            )
                        }"
                    )
                }
                cursor.getString(0)
            }
        }
    }


}